package com.clg.dataSource;

import com.clg.common.jqueryDataTables.DataTablesParam;
import com.clg.common.model.DataSource;
import com.clg.common.jqueryDataTables.DataTablesUtil;
import com.clg.common.model.DatabaseType;
import com.clg.common.tools.RetRes;
import com.clg.common.tools.UUIDTools;
import com.jfinal.core.Controller;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * Created by usercai on 2016/10/10.
 */
public class DataSourceController extends Controller{
    private static Logger log = Logger.getLogger(DataSourceController.class);

    public void index() {
        setAttr("dataBaseTypes",DatabaseType.dao.queryAll());
        render("dataSource/index.html");
    }

    /**
     * 分页查询数据源
     */
    public void queryDataSource(){
        DataTablesParam param = DataTablesUtil.getParam(getRequest());

        renderJson(DataTablesUtil.queryPage(param,DataSource.dao));

    }

    /**
     * 测试数据源
     */
    public void testDataSource(){
        String id = getPara("id");
        DataSourceService service = enhance(DataSourceService.class);
        renderJson(service.testDataSource(id));
    }

    public void testConfigDataSource(){
        String dataSourceTypeID = getPara("dataSourceTypeID");
        String jdbcUrl = getPara("jdbcUrl");
        String user = getPara("user");
        String pass = getPara("password");
        DataSourceService service = enhance(DataSourceService.class);
        renderJson(service.testConfigDataSource(dataSourceTypeID,jdbcUrl,user,pass));
    }

    public void saveOrUpdate(){
        DataSource dataSource = getModel(DataSource.class,"");
        try{
            if(StringUtils.isNotBlank(dataSource.getId())){
                dataSource.update();
            }else{
                dataSource.setId(UUIDTools.genUUIDKey());
                dataSource.save();
            }
        }catch (Exception e){
            renderJson(RetRes.create(false).setMessage(e.getMessage()));
        }
        renderJson(RetRes.create(true));
    }

    public void  queryDataSourceType(){
        renderJson(DatabaseType.dao.queryAll());
    }
}
